﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{    
    m_nCurrentState             = PROCESSEMULATE_DEFAULT;
    m_timeEmulate               = QTime(0, 0, 0, 0);
    m_nMscsElapsed              = 0;

    ui->setupUi(this);

    connect(ui->pushButtonStart, SIGNAL(clicked()), this, SLOT(start()));
    connect(ui->pushButtonStop, SIGNAL(clicked()), this, SLOT(stop()));
    connect(ui->pushButtonPause, SIGNAL(clicked()), this, SLOT(pause()));
    connect(ui->pushButtonResume, SIGNAL(clicked()), this, SLOT(resume()));

    startTimer(10);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::start()
{
    // 初始化定时器
    m_timeEmulate.start();
    m_nMscsElapsed = 0;

    // 改变仿真状态
    m_nCurrentState = PROCESSEMULATE_START;

    // 写公告
    QString strText = tr("emulate start,\t time :%1\n").arg(QTime::currentTime().toString("HH:mm:ss zzz"));
    write(strText);
}

void MainWindow::stop()
{
    if (m_nCurrentState == PROCESSEMULATE_STOP)
    {
        return;
    }

    // 改变仿真状态
    m_nCurrentState = PROCESSEMULATE_STOP;

    // 写公告
    QString strText = tr("emulate stop,\t time :%1\n").arg(QTime::currentTime().toString("HH:mm:ss zzz"));
    write(strText);
}

void MainWindow::pause()
{
    if ( (m_nCurrentState != PROCESSEMULATE_START)
         && (m_nCurrentState != PROCESSEMULATE_RESUME) )
    {
        return;
    }

    // 累加计算仿真持续时间
    m_nMscsElapsed += m_timeEmulate.elapsed();

    // 改变仿真状态
    m_nCurrentState = PROCESSEMULATE_PAUSE;

    // 写公告
    QString strText;
    strText += tr("emulate pause,\t time :%1\n").arg(QTime::currentTime().toString("HH:mm:ss zzz"));
    strText += tr("elapsed :%1(msecs)\n").arg(m_nMscsElapsed);
    write(strText);
}

void MainWindow::resume()
{
    if (m_nCurrentState != PROCESSEMULATE_PAUSE)
    {
        return;
    }

    // 重启计时，累加以往仿真时间
    m_timeEmulate.restart();
    m_timeEmulate.addMSecs(m_nMscsElapsed);

    // 改变仿真状态
    m_nCurrentState = PROCESSEMULATE_RESUME;

    // 写公告
    QString strText;
    strText += tr("emulate resume,\t time :%1\n").arg(QTime::currentTime().toString("HH:mm:ss zzz"));
    write(strText);
}

void MainWindow::write(const QString &strText)
{
    this->ui->textEdit->append(strText);
}

void MainWindow::timerEvent(QTimerEvent *)
{

}
